package com.basis.utils;

import org.apache.commons.lang.StringUtils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成序号
 * @time 2014-11-5下午5:27:23
 */
public class CodeNumberFactory {
	private static Map<String, String> map = new HashMap<String, String>();
	private static String STATNUM = "00001";
	/**
	 * 获取年月日
	 */
	public String getTime() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		DateFormat df = new SimpleDateFormat("YYYY/MM/dd HH:mm:ss.SSS");
		return df.format(cal.getTime());
	}
	/**
	 * 判断序号是否到了最后一个
	 */
	public String getLastSixNum(String s) {
		String rs = s;
		int i = Integer.parseInt(rs);
		i += 1;
		rs = "" + i;
		for (int j = rs.length(); j < 5; j++) {
			rs = StringUtils.leftPad(rs, j + 1, "0");
		}
		return rs;
	}
	/**
	 * 产生不重复的号码 加锁
	 */
	public synchronized String getNum() {
		String yearAMon = getTime().replace(":", "").replace("/", "").replace(".", "").replace(" ", "");
		String last6Num = map.get(yearAMon);
		if (last6Num == null) {
			map.put(yearAMon, STATNUM);
		} else {
			map.put(yearAMon, getLastSixNum(last6Num));
		}
		String num = yearAMon + map.get(yearAMon);
		String No = num.substring(2, num.length());
		return No;
	}
}
